#!/usr/bin/env python
# -*- coding:utf-8 -*- #

#from gevent import monkey
#monkey.patch_all()
from django.core.management import execute_manager
from popcan.core import settings
from popcan.globals.settings import ServerSettings
from popcan.cache.cachedaos import CacheDaoLoader
from popcan.db.daos import DaosLoader
from popcan.redis.redisdaos import RedisDaoLoader
from popcan.helper.uidhelper import UIDLoader
from popcan.helper.loggerhelper import QueueLogger,Module
from popcan.core.halt import HaltManager
import traceback,sys

def prestart():
    # 以参数中指定的端口号对64取模作为serverId
    ports = filter(lambda s:s.startswith('port='),sys.argv)
    if len(ports) > 0:
        port = ports[0].split('=')[1]
        ServerSettings.serverId = int(port) % 64
    
def doLoad():
    try:
        DaosLoader().loadDaos()
        CacheDaoLoader().loadCacheDaos()
        RedisDaoLoader().loadRedisDaos()
        UIDLoader().loadUIDs()
    except:
        QueueLogger().error(Module.Load, 'load failure', traceback.format_exc())
        raise Exception('load error')

def doHalt():
    HaltManager().run()

if __name__ == "__main__":
    prestart()
    try:
        doLoad()
        execute_manager(settings)
    except:
        doHalt()
        